package socdev.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;

public class ProjectContainer implements Runnable{

	Map<String, Project> projects = new HashMap<String, Project>();
	User user;
	Handler handler;
	Runnable handlerRunnable;
	static boolean isUpdating;
	
	public ProjectContainer(User user) {
		this.user = user;
		isUpdating = false;
	}
	
	public synchronized void update(Handler handler, Runnable runnable) {
		if (isUpdating) return;
		isUpdating = true;
		Thread update = new Thread(this);
		
		this.handler = handler;
		this.handlerRunnable = runnable;
		
		update.start();
		
		
	}

	@Override
	public void run() {
		try {
			JSONArray jsonArray = JSonDownloader.getData("http://socdev-dev1.appspot.com/api/groups/", user.getNameValuePairs(new ArrayList<NameValuePair>()));
			projects = new HashMap<String, Project>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Project user = Project.createFromJson(jsonObject);
				projects.put(user.getId(), user);
			}
		
		}catch (JSONException e) {
			e.printStackTrace();
		}
		
		this.handler.post(handlerRunnable);
		isUpdating = false;
	}
	
	public boolean contains(String id) {
		return projects.containsKey(id);
		
	}
	
	public Project get(String id) {
		return projects.get(id);
	}
	
	
	public List<Project> getAll(){
		return new ArrayList<Project>(projects.values());
		
	}

}
